package net.osin.playscalajs.TableControl

import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding.{Var, Vars}
import org.lrng.binding.html
import org.scalajs.dom.html.Div
import org.scalajs.dom.raw.Event
import scalaz.Divide

class View(var table: TableTrait)
{


  // injection
  val headers = table.headers
  val totalCount = table.totalCount
  val contents = table.contents

  def generate(page_index: Int, page_size: Int) = table.generate(page_index, page_size)


  // local variances
  val showNextPage = Var(true)
  val showPrePage = Var(true)
  val pageIndex = Var(1)
  val pageSize = Var(10)
  val totalPage = Math.ceil(25.toFloat / pageSize.value)

  // init view
  generate(pageIndex.value, pageSize.value)

  // event
  val addRowHandler = {
    event: Event =>
    table.addRow(event)
  }

  val prePage = {
    event: Event =>
      if (pageIndex.value > 1)
      {
        showNextPage.value = true
        pageIndex.value -= 1
        contents.value.clear()
        generate(pageIndex.value, pageSize.value)
      }
      else
        showPrePage.value = false

  }
  val nextPage = {
    event: Event =>
      if (pageIndex.value < totalPage)
      {
        showPrePage.value = true
        pageIndex.value += 1
        contents.value.clear()
        generate(pageIndex.value, pageSize.value)
      }
      else
        showNextPage.value = false
  }

  @html
  def mytable = {
    <div>
      <button onclick={addRowHandler}>Add a row</button>
      <button style={ if (showPrePage.bind) "" else "none" } onclick={prePage}>上一页</button>
      <button style={ if (showNextPage.bind) "" else "none" } onclick={nextPage}>下一页</button>
      <table class="layui-table-view">
        <tr>
          {
          for (head <- headers)
            yield <th>{head}</th>
          }
        </tr>
        {
        for (content <- contents) yield
          <tr>
            {
            for (con <- content) yield
              <td>{con.bind}</td>
            }
          </tr>
        }
      </table>

    </div>
  }

  @html
  def render:Binding[Div] = {
    <div>
      {mytable.bind}
    </div>
  }
}
